package com.vce.web.security;

import com.vce.User;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
import com.vce.SecurityManager;
/**
 * Date: 03-13-2007
 * @author Larry Ruiz
 */
public class SecurityContextFilter extends OncePerRequestFilter implements Filter {
    public static final String SECURITY_CONTEXT_ATTRIBUTE = "currentUser";
    private String dontApplyFor;
    private String entryPoint;
    private SecurityManager securityManager;
    
    public void setDontApplyFor(String dontApplyFor){
        this.dontApplyFor = dontApplyFor;
    }
    
    public void setEntryPoint(String entryPoint){
        this.entryPoint = entryPoint;
    }
    
    public void setSecurityManager(SecurityManager securityManager){
        this.securityManager = securityManager;
    }

    public boolean shouldNotFilter(HttpServletRequest request){
        if(securityManager.getCurrentUser() != null){
            return true;
        }
        String uri = request.getRequestURI();
        if(entryPoint != null && uri.endsWith(entryPoint)){
            return true;
        }
        
        if(dontApplyFor == null){
            return false;
        }
        
        int length = request.getContextPath().length();
        uri = uri.substring(length);        
        return uri.matches(dontApplyFor);
    }    
    
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        User user = (User)request.getSession().getAttribute(SECURITY_CONTEXT_ATTRIBUTE);
        if(user != null){
            securityManager.setCurrentUser(user);
        }
        
        try{
            chain.doFilter(request, response);
        }finally{
            
            if(user == null && securityManager.getCurrentUser() != null){
                //that means that the user has logged in, so grab into the session
                request.getSession().setAttribute(SECURITY_CONTEXT_ATTRIBUTE, securityManager.getCurrentUser());
            }else if(user != null && securityManager.getCurrentUser() == null){
                //that means that the user has logged out
                request.getSession().removeAttribute(SECURITY_CONTEXT_ATTRIBUTE);
                request.getSession().invalidate();
            }
            
            securityManager.clearContext();
        }    
    }
}
